import wx
import message_log
import pandas as pd
import os


class RegistFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=1, title='注册', size=(500, 400),
                          style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX)
        self.SetBackgroundColour('white')
        # self.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)  # 设置各组件的注释
        self.log = message_log.Log()
        self.id = None

        sizer = wx.BoxSizer(wx.VERTICAL)

        # label = wx.StaticText(self, -1, "用户注册")
        # label.SetHelpText("This is the help text for the label")
        # sizer.Add(label, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        texts = ['账号:', '密码:']
        self.addbox(sizer, texts)

        box = wx.BoxSizer(wx.HORIZONTAL)
        label = wx.StaticText(self, -1, "类型:")
        box.Add(label, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
        typelist = ['学生', '教师', '管理员']
        self.ch = wx.Choice(self, -1, (100, 50), choices=typelist)
        box.Add(self.ch, 1, wx.ALIGN_CENTRE | wx.ALL, 5)
        sizer.Add(box, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
        self.Bind(wx.EVT_CHOICE, self.choice, self.ch)  # 绑定事件

        # line = wx.StaticLine(self, -1, size=(20, -1), style=wx.LI_HORIZONTAL) # 画根分界线
        # sizer.Add(line, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.TOP, 5)

        btnsizer = wx.StdDialogButtonSizer()    # 确认取消按钮

        if wx.Platform != "__WXMSW__":
            btn = wx.ContextHelpButton(self)
            btnsizer.AddButton(btn)

        btn1 = wx.Button(self, wx.ID_OK)
        # btn.SetHelpText("The OK button completes the dialog")
        btn1.SetDefault()
        btnsizer.AddButton(btn1)
        self.Bind(wx.EVT_BUTTON, self.check, btn1)

        btn2 = wx.Button(self, wx.ID_CANCEL)
        # btn.SetHelpText("The Cancel button cancels the dialog. (Cool, huh?)")
        btnsizer.AddButton(btn2)
        self.Bind(wx.EVT_BUTTON, self.cancel, btn2)
        btnsizer.Realize()

        sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)

        self.SetSizer(sizer)
        sizer.Fit(self)

    def addbox(self, sizer, texts):
        for text in texts:
            box = wx.BoxSizer(wx.HORIZONTAL)
            label = wx.StaticText(self, -1, text)
            # label.SetHelpText("This is the help text for the label")
            box.Add(label, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
            if '账号' in text:
                self.username = wx.TextCtrl(self, -1, "", size=(80, -1))
                # text.SetHelpText("Here's some help text for field #1")
                box.Add(self.username, 1, wx.ALIGN_CENTRE | wx.ALL, 5)
            elif '密码' in text:
                self.password = wx.TextCtrl(self, -1, "", size=(80, -1))
                # text.SetHelpText("Here's some help text for field #1")
                box.Add(self.password, 1, wx.ALIGN_CENTRE | wx.ALL, 5)
            sizer.Add(box, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)

    def choice(self, event):
        print(event.GetString())
        self.id = event.GetString()

    def check(self, event):
        username = self.username.GetValue()
        password = self.password.GetValue()
        if username == '' or password == '':
            self.log.WriteText('账号或密码为空')
        elif self.id == None:
            self.log.WriteText('请选择身份')
        else:
            if os.path.exists('账号密码本.xlsx'):    # 有则读取判断是否已有该账号
                df = pd.read_excel('账号密码本.xlsx')
                if username in list(df['账号']):
                    self.log.WriteText("已存在该账号，注册失败")
                elif self.id == '管理员' and '管理员' in list(df['身份']):
                    self.log.WriteText('已有管理员，注册失败')
                else:
                    df.loc[df.shape[0]] = {'账号': username, '密码': password, '身份': self.id}
                    df.to_excel('账号密码本.xlsx', index=False)
                    self.log.WriteText('注册成功')
                    self.Destroy()
            else:   # 无则直接写入Excel
                df = pd.DataFrame([{'账号': username, '密码': password, '身份': self.id}])
                df = df[['账号', '密码', '身份']]
                df.to_excel('账号密码本.xlsx', index=False)
                self.log.WriteText("注册成功")
                self.Destroy()

    def cancel(self, event):
        self.Destroy()
